use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use include_dir::Dir;
use text_placeholder::Template;

///初始化模板文件，将模板文件输出到目标目录，并根据参数替换文件内容
pub fn init_template(dir: &Dir, docs_name: &str) -> Result<(), Box<dyn Error>> {
    for entry in dir.entries() {
        if let Some(x) = entry.as_dir() {
            init_template(x, docs_name)?;
        } else {
            let file_path = entry.path();
            let mut output_path_buf = PathBuf::new();
            output_path_buf.push(docs_name);
            output_path_buf.push(file_path);
            let output_path = output_path_buf.to_str().unwrap();
            let parent_dir = std::path::Path::new(output_path).parent().unwrap();
            fs::create_dir_all(parent_dir)?;
            let mut file = File::create(output_path)?;
            if let Some(content) = entry.as_file().unwrap().contents_utf8() {
                //替换文字
                let tt = Template::new_with_placeholder(content, "<%", "%>");
                let mut map = HashMap::new();
                map.insert("name", docs_name);
                map.insert("title", docs_name);
                let new_content = tt.fill_with_hashmap(&map);
                file.write_all(new_content.as_bytes())?;
            } else {
                file.write_all(entry.as_file().unwrap().contents())?;
            }
        }
    }
    Ok(())
}
